package com.qiaofang.applet.filter;

import com.alibaba.fastjson.JSON;
import com.qiaofang.applet.common.constant.ResponseCode;
import com.qiaofang.applet.common.context.QfContext;
import com.qiaofang.applet.common.context.QfContextHolder;
import com.qiaofang.applet.common.context.QfContextProvider;
import com.qiaofang.applet.common.dto.DataResponse;
import com.qiaofang.applet.common.util.RedisUtil;
import com.qiaofang.applet.service.other.domain.CityCompany;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.service.CityCompanyService;
import com.qiaofang.applet.service.other.service.CorporationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * PC官网地址过滤器
 *
 * @author QF2019
 */
@Slf4j
@Component
public class WebsiteFilter extends GenericFilterBean {

    @Autowired
    private RedisUtil redisUtils;

    @Autowired
    private QfContextProvider contextProvider;

    @Autowired
    private CityCompanyService cityCompanyService;

    @Autowired
    private CorporationService corporationService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1、判断是否已经存在QfContext上下文，如果存在则继续执行后面的逻辑
        // 2、上下文件不存在，则从header里取出域名，然后初始化QfContext上下文
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        log.info("请求web地址-path:{},context:{}", request.getRequestURI(), JSON.toJSONString(QfContextHolder.getContext()));
        if (existQfContext()) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }


        String webDomain = request.getHeader("qfhost");
        log.info("请求web地址-qfhost:{},path:{}", webDomain, request.getRequestURI());
        if (StringUtils.isEmpty(webDomain)) {
            webDomain = request.getHeader("Host");
        }
        int index = webDomain.indexOf(":");
        if (index > 0) {
            webDomain = webDomain.substring(0, index);
        }
        log.info("请求web地址:{},path:{}", webDomain, request.getRequestURI());

        // 3、通过域名查询对应的集团信息信息,并初始化QfContext上下文
        if (!initQfContext(webDomain)) {
            writeResponse(servletResponse);
            return;
        }
        //log.info("用户鉴权通过, context:{}", JSON.toJSONString(contextProvider.getContext()));
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        contextProvider.removeContext();
    }

    /**
     * 判断QfContext是否存在
     *
     * @return
     */
    private static boolean existQfContext() {
        QfContext qfContext = QfContextHolder.getContext();
        if (qfContext == null) {
            return false;
        }

        return StringUtils.isNotEmpty(qfContext.getCorporationCode()) && StringUtils.isNotEmpty(qfContext.getCityCode());
    }

    /**
     * 据集团官网查询集团授权信息
     *
     * @param webDomain
     * @return
     */
    private boolean initQfContext(String webDomain) {
        // 1、根据域名查询对应的城市
        CityCompany cityCompany = cityCompanyService.getCityCompany(webDomain);
        if (cityCompany == null) {
            return false;
        }
        contextProvider.setContext(new QfContext(
                // 集团code
                cityCompany.getCorporationCode(),
                // 公司uuid
                cityCompany.getCompanyUuid(),
                // 城市code
                cityCompany.getCityCode(),
                // 城市名称
                cityCompany.getCompanyCity(),
                // 当前请求的域名
                webDomain));
        return true;
    }

    /**
     * 输出响应结果
     *
     * @param response
     * @throws IOException
     */
    private void writeResponse(ServletResponse response) throws IOException {
        DataResponse dataResponse = DataResponse.fail(ResponseCode.AUTH_FAIL.getStatus(), ResponseCode.AUTH_FAIL.getMessage());
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSON.toJSONString(dataResponse));
    }
}
